package com.schoolcloud.serve.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolcloud.serve.entity.SpuCategory;
import com.schoolcloud.serve.service.SpuCategoryService;
import com.schoolcloud.serve.mapper.SpuCategoryMapper;
import com.schoolcloud.serve.vo.SpuCategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author hongmizfb
* @description 针对表【spu_category(分类表)】的数据库操作Service实现
* @createDate 2025-04-12 17:11:02
*/
@Service
public class SpuCategoryServiceImpl extends ServiceImpl<SpuCategoryMapper, SpuCategory>
    implements SpuCategoryService{

    @Override
    public List<SpuCategoryVO> getTreeList() {
        List<SpuCategory> list = lambdaQuery().list();
        List<SpuCategoryVO> allList = list.stream().map(item -> {
            SpuCategoryVO vo = new SpuCategoryVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).toList();
        List<SpuCategoryVO> parentList = list.stream().filter(item -> item.getParentId() == 0).map(item -> {
            SpuCategoryVO vo = new SpuCategoryVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).toList();
        return convertToTree(parentList, allList);
    }
    public List<SpuCategoryVO> convertToTree(List<SpuCategoryVO> parentList, List<SpuCategoryVO> list){
        if (parentList==null || parentList.size()==0){
            return null;
        }
        parentList.forEach(parentItem -> {
            List<SpuCategoryVO> spuCategoryVOS = list.stream().filter(childItem -> childItem.getParentId().equals( parentItem.getCategoryId())).toList();
            if (spuCategoryVOS.size() > 0) {
                //            递归继续遍历子集合
                convertToTree(spuCategoryVOS, list);
            }
            parentItem.setChildren(spuCategoryVOS);
        });
        return parentList;
    }
}




